package com.cskaoyan.service.wx;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.bo.WxOrderCommentBO;
import com.cskaoyan.bean.bo.WxOrderListBO;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.util.HandleOptionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author : gao
 * @since: 2022/10/14  16:44
 */
@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCartMapper marketCartMapper;

    @Override
    public CommonData<WxOrderListVO> list(WxOrderListBO wxOrderListBO) {
        Integer showType = wxOrderListBO.getShowType();
        Integer page = wxOrderListBO.getPage();
        Integer limit = wxOrderListBO.getLimit();

        PageHelper.startPage(page, limit);
        List<WxOrderListVO> orderListVOS = orderMapper.selectListByOrderStatus(showType);
        PageInfo<WxOrderListVO> pageInfo = new PageInfo<>(orderListVOS);

        for (WxOrderListVO orderInfo : orderListVOS) {
            orderInfo.setIsGroupin(false);
            int orderStatus = orderMapper.selectOrderStatus(orderInfo.getId());
            if (orderStatus == 101) {
                orderInfo.setOrderStatusText("待付款");
            } else if (orderStatus == 102 || orderStatus == 103) {
                orderInfo.setOrderStatusText("订单已取消");
            } else if (orderStatus == 201 || orderStatus == 202) {
                orderInfo.setOrderStatusText("已付款");
            } else if (orderStatus == 203) {
                orderInfo.setOrderStatusText("已退款");
            } else if (orderStatus == 301) {
                orderInfo.setOrderStatusText("已发货");
            } else if (orderStatus == 401 || orderStatus == 402) {
                orderInfo.setOrderStatusText("已收货");
            }

            List<WxGoodOfOrderListVO> goodOfOrderListVOS = orderGoodsMapper.selectGoodsByOrderId(orderInfo.getId());
            orderInfo.setGoodsList(goodOfOrderListVOS);

            WxHandleOptionVO optionVO = HandleOptionUtil.handleOptionVO(orderStatus);
            orderInfo.setHandleOption(optionVO);
        }

        CommonData<WxOrderListVO> commonData = new CommonData<>();
        commonData.setTotal((int) pageInfo.getTotal());
        commonData.setPages(pageInfo.getPages());
        commonData.setLimit(limit);
        commonData.setPage(page);
        commonData.setList(orderListVOS);

        return commonData;
    }

    @Override
    public WxOrderDetailVO detail(Integer orderId) {

        //获得orderInfo
        WxOrderInfoOfOrderDetailVO orderInfo = orderMapper.selectOrderInfoById(orderId);
        int orderStatus = orderMapper.selectOrderStatus(orderId);
        if (orderStatus == 101) {
            orderInfo.setOrderStatusText("待付款");
        } else if (orderStatus == 102 || orderStatus == 103) {
            orderInfo.setOrderStatusText("订单已取消");
        } else if (orderStatus == 201 || orderStatus == 202) {
            orderInfo.setOrderStatusText("已付款");
        } else if (orderStatus == 203) {
            orderInfo.setOrderStatusText("已退款");
        } else if (orderStatus == 301) {
            orderInfo.setOrderStatusText("已发货");
        } else if (orderStatus == 401 || orderStatus == 402) {
            orderInfo.setOrderStatusText("已收货");
        }
        WxHandleOptionVO optionVO = HandleOptionUtil.handleOptionVO(orderStatus);
        orderInfo.setHandleOption(optionVO);

        //获得orderGoods
        List<MarketOrderGoods> orderGoods = orderGoodsMapper.selectByOrderId(orderId);

        WxOrderDetailVO orderDetailVO = new WxOrderDetailVO();
        orderDetailVO.setOrderInfo(orderInfo);
        orderDetailVO.setOrderGoods(orderGoods);
        return orderDetailVO;
    }

    @Override
    public void refund(Integer orderId) {
        int orderStatus = 203;
        orderMapper.updateOrderStatus(orderStatus, orderId);
    }

    @Override
    public void confirm(Integer orderId) {
        int orderStatus = 401;
        orderMapper.updateOrderStatus(orderStatus, orderId);
    }

    @Override
    public void delete(Integer orderId) {
        int orderStatus = 666;
        orderMapper.updateOrderStatus(orderStatus, orderId);
    }

    @Override
    public void cancel(Integer orderId) {
        int orderStatus = 102;
        orderMapper.updateOrderStatus(orderStatus, orderId);
    }

    /**
     * 提交订单的业务逻辑
     *
     * @param map
     * @return com.cskaoyan.bean.vo.WxOrderSubmitVo
     * @author gatsby
     * @since 2022/10/16 20:28
     */
    @Transactional
    @Override
    public WxOrderSubmitVo submit(Map map) {
        Session session = SecurityUtils.getSubject().getSession();
        WxCartCheckedVo wxCartCheckedVo = (WxCartCheckedVo) session.getAttribute("wxCartCheckedVo");
        MarketAddress checkedAddress = wxCartCheckedVo.getCheckedAddress();
        List<MarketCart> checkedGoodsList = wxCartCheckedVo.getCheckedGoodsList();
        MarketOrder marketOrder = new MarketOrder();

        //用户id
        MarketUser marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Integer userId = marketUser.getId();
        marketOrder.setUserId(userId);
        //订单编号
        Instant instant = new Date().toInstant();
        String s = instant.toString();
        marketOrder.setOrderSn(s);
        //订单状态
        marketOrder.setOrderStatus(Short.valueOf("101"));
        //售后状态
        marketOrder.setAftersaleStatus(Short.valueOf("0"));
        //收货人昵称
        marketOrder.setConsignee(checkedAddress.getName());
        //收货人手机号
        marketOrder.setMobile(checkedAddress.getTel());
        //收货人地址
        String address=checkedAddress.getProvince()+checkedAddress.getCity()+checkedAddress.getCounty()+checkedAddress.getAddressDetail();
        marketOrder.setAddress(address);
        //用户订单留言
        String message = (String) map.get("message");
        marketOrder.setMessage(message);
        //商品总费用
        marketOrder.setGoodsPrice(wxCartCheckedVo.getGoodsTotalPrice());
        //配送费
        marketOrder.setFreightPrice(wxCartCheckedVo.getFreightPrice());
        //优惠券减免减免
        marketOrder.setCouponPrice(wxCartCheckedVo.getCouponPrice());
        //积分减免
        marketOrder.setIntegralPrice(new BigDecimal(0));
        //团购减免
        marketOrder.setGrouponPrice(new BigDecimal(0));
        //订单费用
        marketOrder.setOrderPrice(wxCartCheckedVo.getActualPrice());
        //实付费用
        marketOrder.setActualPrice(wxCartCheckedVo.getActualPrice());
        //微信付款编号
        int i = new Date().hashCode();
        marketOrder.setPayId(String.valueOf(i));
        //微信付款时间
        marketOrder.setPayTime(new Date());
        //创建时间
        marketOrder.setAddTime(new Date());
        //更新时间
        marketOrder.setUpdateTime(new Date());
        //逻辑删除
        marketOrder.setDeleted(false);

        //插入数据库order表
        orderMapper.insertSelective(marketOrder);
        //插入数据库order_goods表


        for (MarketCart marketCart : checkedGoodsList) {
            MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
            //订单表id
            marketOrderGoods.setOrderId(marketOrder.getId());
            //商品表id
            marketOrderGoods.setGoodsId(marketCart.getGoodsId());
            //商品名称
            marketOrderGoods.setGoodsName(marketCart.getGoodsName());
            //商品编号
            marketOrderGoods.setGoodsSn(marketCart.getGoodsSn());
            //商品货物表的货物id
            marketOrderGoods.setProductId(marketCart.getProductId());
            //商品货物的购买数量
            marketOrderGoods.setNumber(marketCart.getNumber());
            //商品货物的售价
            marketOrderGoods.setPrice(marketCart.getPrice());
            //商品货物的规格列表
            marketOrderGoods.setSpecifications(marketCart.getSpecifications());
            //商品货物图片或者商品图片
            marketOrderGoods.setPicUrl(marketCart.getPicUrl());
            //订单商品评论
            //创建时间
            marketOrderGoods.setAddTime(new Date());
            //更新时间
            marketOrderGoods.setUpdateTime(new Date());
            //逻辑删除
            marketOrderGoods.setDeleted(false);

            //插入数据库market_order_goods
            orderGoodsMapper.insertSelective(marketOrderGoods);

        }


        //将对应的优惠券状态设为已使用
        Integer userCouponId = (Integer) map.get("userCouponId");
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        MarketCouponUserExample example = new MarketCouponUserExample();
        example.setDistinct(true);
        MarketCouponUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(userCouponId);
        marketCouponUser.setStatus(Short.valueOf("1"));


        marketCouponUserMapper.updateByExampleSelective(marketCouponUser,example);
        //将商品对应的购物车删除掉(逻辑删除)
        for (MarketCart marketCart : checkedGoodsList) {
            MarketCart marketCart1 = new MarketCart();
            marketCart1.setId(marketCart.getId());
            marketCart1.setDeleted(true);
            marketCartMapper.updateByPrimaryKey(marketCart1);
        }


        WxOrderSubmitVo wxOrderSubmitVo = new WxOrderSubmitVo();
        wxOrderSubmitVo.setOrderId(marketOrder.getId());
        wxOrderSubmitVo.setGrouponLinkId(0);
        return wxOrderSubmitVo;
    }

    @Override
    public void prepay(Integer orderId) {

    }

    @Override
    public MarketOrderGoods goods(Integer orderId, Integer goodsId) {
        MarketOrderGoods orderGoods = orderGoodsMapper.selectGoodsByOrderIdAndGoodsId(orderId, goodsId);
        return orderGoods;
    }

    //商品评论
    @Override
    public void comment(Integer userId, WxOrderCommentBO wxOrderCommentBO) {
        Integer valueId = orderGoodsMapper.selectGoodsSnById(wxOrderCommentBO.getOrderGoodsId());

        MarketComment marketComment = new MarketComment();
        marketComment.setValueId(valueId);
        marketComment.setContent(wxOrderCommentBO.getContent());
        marketComment.setUserId(userId);
        marketComment.setHasPicture(wxOrderCommentBO.getHasPicture());
        marketComment.setPicUrls(wxOrderCommentBO.getPicUrls());
        Date date = new Date();
        marketComment.setAddTime(date);
        marketComment.setUpdateTime(date);

        int count = commentMapper.insertSelective(marketComment);

    }


}
